<?php

namespace Beerus\Modules\NewProduct\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\NewProduct\NewProductWikiModel;
use Biz\model\NewProduct\NewProductWinnerListModel;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\module\Packages\Logistics\TrackingMore;
use Biz\service\NewProduct\NewProductWinnerListService;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\User;
use Doraemon\model\Sysmsg;

class WinnerController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        Admin::script($this->toShipScript());
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $page = $params['page'] ?? 1;
        $nid = $params['nid'] ?? 0;
        $list = [];
        if ($nid > 0) {
            $where = [
                'nid' => $nid,
                'winner_status[!]' => NewProductWinnerListModel::DELETE,
                'LIMIT' => [($page - 1) * $page_size, $page_size],
            ];
            $field = ['id', 'uid', 'address_id', 'courier_id', 'tracking_number', 'addtime', 'winner_status', 'jd_num'];
            $list = NewProductWinnerListService::getWinnerList($field, $where, 0, $page * $page_size);
        }
        $type = NewProductWikiModel::get('type', ['id' => $nid]);
        $jdCardNum = NewProductWinnerListService::getCountJdCardByNid([$nid]);
        $jdCardNum = $jdCardNum[$nid] ?? 0;
        $count = $list['total'] ?? 0;
        $list = $list['list'] ?? [];
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $type, $jdCardNum) {
                //显示当前页的序号
                $grid->number('序号');
                $grid->rows(function ($row, $number) {
                    $row->column('number', $number + 1);
                });

                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disableCreateButton();
                if ($type == NewProductWikiModel::SUPER_PDT || $jdCardNum > 0) {
                    $grid->disableActions();
                }
                $grid->column('id', 'ID');
                $grid->column('uid', '用户uid');
                $grid->column('nickName', '用户昵称');
                $grid->column('jd_num', '京东卡');
                $grid->column('address_info_name', '收货人');
                $grid->column('address_info_address', '收货地址');
                $grid->column('address_info_tel', '收货人联系电话');
                $grid->column('couriers_info_courier_name', '物流公司');
                $grid->column('tracking_number', '物流单号');
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($type) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    if ($actions->row->winner_status == NewProductWinnerListModel::NOT_SEND_PRIZE && $actions->row->jd_num == '') {
                        $actions->prepend('<a class="fa fa-edit to-ship" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>填写物流单号</a>');
                    }
                });
            }
        );
        $tab = new Tab();
        $tab->add('中奖名单', $grid->render(), true);
        $tab->addLink('新品速递活动 ', url('/admin/newProduct/index'), false);
        $content->row($tab);
        return $content
            ->header('中奖名单')
            ->breadcrumb(['text' => '新品速递审核', 'url' => '/admin/newProduct/winnerList']);
    }

    private function toShipScript(): string
    {
        return <<<SCRIPT
        $('.to-ship').unbind('click').click(function(){
            var id=$(this).data('id');
            layer.open({
                type: 2,
                title: '',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['600px', '600px'],
                content: '/admin/newProduct/winnerList/'+id+'/editShip',
            });
        });
SCRIPT;
    }

    /**
     * 填写物流单号
     * @param \Illuminate\Http\Request $request
     * @param \App\Admin\Extensions\WorkContent $content
     * @param $id
     * @return \App\Admin\Extensions\WorkContent
     */
    public function editShip(Request $request, WorkContent $content, $id): WorkContent
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }

        $where = [
            'id' => $id,
            'winner_status[!]' => NewProductWinnerListModel::DELETE,
        ];
        $field = ['id', 'uid', 'address_id', 'courier_id', 'prize_name'];
        $info = NewProductWinnerListService::getWinnerInfo($field, $where);
        $form = new Form($info);
        $form->hidden('id');
        $form->hidden('uid');
        $couriers = NewProductWinnerListService::handleData($info['couriers'] ?? [], 'courier_id',
            'courier_name');
        $form->text('nickName', '用户昵称')->disable();
        $form->text('address_info_name', '收货人')->disable();
        $form->text('address_info_tel', '收货人联系电话')->disable();
        $form->text('address_info_address', '收货人地址')->disable();
        $form->select('courier', '物流公司')->options($couriers)->required();
        $form->text('tracking_number', '物流单号')->required();
        $form->action('/admin/newProduct/winnerList/saveShip');

        return $content
            ->body($form);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function saveShip(Request $request)
    {
        $id = $request->input('id', 0);//中奖名单主键id
        $courierId = $request->input('courier', 0);//物流公司id
        $trackingNumber = $request->input('tracking_number', '');//物流单号
        $uid = $request->input('uid', 0);//uid

        if (!$id || !$courierId || !$trackingNumber) {
            $error = new MessageBag(['title' => '参数错误']);

            return redirect("/admin/newProduct/winnerList/{$id}/editShip")->with(compact('error'));
        }
        $courierInfo = mShopCourier::getCourier('*', ['courier_id' => $courierId]);
        if ($courierInfo) {
            $carrierCode = $courierInfo['trackingmore_code'];
            //创建物流信息
            $data = TrackingMore::createTracking($carrierCode, $trackingNumber,
                ['logistics_channel' => TrackingMore::LOGISTICS_CHANNEL_NEW_PRODUCT]);
            //更新中奖名单数据
            if ($data['meta']['code'] == 200) {
                NewProductWinnerListModel::update([
                    'courier_id' => $courierId,
                    'tracking_number' => $trackingNumber,
                    'winner_status' => NewProductWinnerListModel::SEND_PRIZE,
                ], ['id' => $id]);
                //发送通知
                if ($uid > 0) {
                    $link = Hhzurl::getDomain() . '/brand/new-product-express/my-product';
                    $link = LinkFormat::encryptionLink($link);
                    $title = '新品速递奖品已寄出';

                    $detail = "新品速递奖品「京东卡」已寄出，物流公司：{$courierInfo['courier_name']},物流单号：{$trackingNumber}，请注意查收。";
                    $data = [
                        'msgCode' => 0,
                        'to_uid' => $uid,
                        'msgParams' => [
                            'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
                            'title' => $title,
                            'detail' => $detail,
                            'link' => $link,
                            'type' => Sysmsg::TYPE_SYS_MSG,
                        ],
                    ];
                    \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', $data,
                        \Doraemon\cache\Queue::QUEUE_DORAEMON);
                }
            } else {
                $error = new MessageBag(['title' => $data['meta']['message']]);

                return redirect("/admin/newProduct/winnerList/{$id}/editShip")->with(compact('error'));
            }
        }
        $success = new MessageBag(['title' => '操作成功']);

        return redirect('/admin/newProduct/winnerList/' . $id . '/editShip?code=1')->with(compact('success'));
    }
}